<?php


namespace App\Http\Controllers\Staff;


use App\Http\Controllers\Controller;
use App\Models\AppVersion;
use App\Models\CommodityOrder;
use App\Models\CommodityOrderAssign;
use App\Models\Enterprise;
use App\Models\Information;
use App\Models\Staff;
use App\Models\StaffTimeLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StaffController extends Controller
{
    public function attestation(Request $request)
    {

        $type = $request->input('type');
        $staffId = $request->input('staff_id');

        DB::beginTransaction();

        try {
            //身份认证
            if ($type == 1) {
                $idcar = $request->input('id_number');//身份证号
                if (!$this->isCreditNo($idcar)) {
                    return makeResponse([], '身份证错误', 404);
                }
                $surname = $request->input('surname');//姓
                $name = $request->input('name');//名字
                $work_type = $request->input('work_type');//工种
                $just_idk = $request->input('just_idk');
                $back_idk = $request->input('back_idk');

                $data = [
                    'id_number' => $idcar,
                    'surname' => $surname,
                    'name' => $name,
                    'just_idk' => $just_idk,
                    'back_idk' => $back_idk,
                    'work_type' => $work_type,
                    'is_idcar' => 1,
                ];
                $informationData = [
                    'title' => '通知消息',
                    'content' => '您好，恭喜你通过‘的装’师傅端的身份认证和技能认证',
                    'staff_id' => $staffId
                ];
            }
            //头像认证
            if ($type == 2) {
                $head = $request->input('head');//头像
                $informationData = [
                    'title' => '通知消息',
                    'content' => '您好，恭喜你通过‘的装’师傅端的头像认证',
                    'staff_id' => $staffId
                ];
                $data = [
                    'head' => $head,
                    'is_head' => 1,
                ];
            }
            //企业
            if ($type == 3) {
                $enterprise_name = $request->input('enterprise_name');
                $enterprise_code = $request->input('enterprise_code');
                $enterprise_img = $request->input('enterprise_img');
                $informationData = [
                    'title' => '通知消息',
                    'content' => '您好，恭喜你通过‘的装’师傅端的企业认证。',
                    'staff_id' => $staffId
                ];
                $data = [
                    'is_enterprise' => 1,
                ];
                Enterprise::createOne([
                    'enterprise_name' => $enterprise_name,
                    'enterprise_code' => $enterprise_code,
                    'enterprise_img' => $enterprise_img,
                    'staff_id' => $staffId,
                ])->save();
            }
            Staff::where('id', $staffId)->update($data);
            Information::createOne($informationData)->save();
            DB::commit();
            return makeResponse([], '提交成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }


    public function information(Request $request)
    {
        $staffId = $request->input('staff_id');
        $information = information::where('staff_id', $staffId)->orderBy('created_at', 'desc')->paginate(10);
        return makeResponse($information, '查询成功', 200);

    }

    public function rushOrder(Request $request)
    {
        $staffId = $request->input('staff_id');
        $orderId = $request->input('order_id');
        $lng = $request->input('lng');//经度
        $lat = $request->input('lat');//纬度


        DB::beginTransaction();
        try {
            $order = CommodityOrder::where('id', $orderId)->first();
            if ($order->order_status != 2) {
                return makeResponse([], '订单错误', 404);
            }
            CommodityOrder::where('id', $orderId)->update(['is_assign' => 1, 'order_status' => 3, 'send_at' => date('Y-m-d H:i:s')]);
            CommodityOrderAssign::createOne([
                'staff_id' => $staffId,
                'order_id' => $orderId,
                'lng' => $lng,
                'lat' => $lat

            ])->save();
            DB::commit();
            return makeResponse([], '抢单成功', 200);
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->makeResponse([], $exception->getMessage() . ' [LINE]:' . $exception->getLine(), 500);
        }
    }

    public function serviceList(Request $request)
    {
        $staffId = $request->input('staff_id');
        $order = CommodityOrder::with('staff')->where('order_status', 3)->whereHas('staff', function ($query) use ($staffId) {
            $query->where('staff_id', $staffId);
        })->orderBy('updated_at', 'desc')->paginate(10);

        foreach ($order as &$v) {

            $v->remaining_time = strtotime($v->created_at) + 5400 - time();
            if ($v->remark_img) {
                $v->remark_img = json_decode($v->remark_img);
            } else {
                $v->remark_img = [];
            }
        }
        return makeResponse($order, '查询成功', 200);
    }

    public function orderList(Request $request)
    {
        $staffId = $request->input('staff_id');
        $status = $request->input('status');//3-未完成/已接单(待服务);4-已完成/已确认(已服务);5,已关闭已取消
        if ($status == 3) {
            $order = CommodityOrder::with('staff')->where('order_status', $status)->whereHas('staff', function ($query) use ($staffId) {
                $query->where('staff_id', $staffId);
            })->orderBy('send_at', 'desc')->paginate(10);
        } elseif ($status == 4) {
            $order = CommodityOrder::with('staff')->where('order_status', $status)->whereHas('staff', function ($query) use ($staffId) {
                $query->where('staff_id', $staffId);
            })->orderBy('finished_at', 'desc')->paginate(10);
        } elseif ($status == 5) {
            $order = CommodityOrder::with('staff')->where('order_status', $status)->whereHas('staff', function ($query) use ($staffId) {
                $query->where('staff_id', $staffId);
            })->orderBy('updated_at', 'desc')->paginate(10);
        }


        foreach ($order as &$v) {
            $v->remaining_time = strtotime($v->created_at) + 5400 - time();
            if ($v->remark_img) {
                $v->remark_img = json_decode($v->remark_img);
            } else {
                $v->remark_img = [];
            }
        }
        return makeResponse($order, '抢单成功', 200);
    }

    public function timeLog(Request $request)
    {

        $staffId = $request->input('staff_id');
        $type = $request->input('type');
        if ($type == 1) {
            StaffTimeLog::createOne(['staff_id' => $staffId, 'start_time' => time()])->save();
            return makeResponse([], '开始成功', 200);
        } else {
            $logs = StaffTimeLog::where('staff_id', $staffId)->orderBy('id', 'desc')->first();

            $today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

            if ($logs->start_time < $today_start) {//昨天开始的单
                StaffTimeLog::where('id', $logs->id)->update(['end_time' => $today_start - 1, 'seconds' => $today_start - $logs->start_time]);
                StaffTimeLog::createOne(['staff_id' => $staffId, 'start_time' => $today_start, 'end_time' => time()])->save();
            } else {
                $seconds = time() - $logs->start_time;
                StaffTimeLog::where('id', $logs->id)->update(['end_time' => time(), 'seconds' => $seconds]);
            }


            return makeResponse([], '结束成功', 200);
        }
    }

    public function online(Request $request)
    {
        $staffId = $request->input('staff_id');
        $logs = StaffTimeLog::where('staff_id', $staffId)->get();
        $today = 0;
        $week = 0;
        $month = 0;
        $total = 0;
        $today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $week_start = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y'));
        $month_start = mktime(0, 0, 0, date('m'), 1, date('Y'));

        foreach ($logs as $v) {
            if ($v->start_time >= $today_start) {
                $today += $v->seconds;
            }
            if ($v->start_time > $week_start) {
                $week += $v->seconds;
            }
            if ($v->start_time >= $month_start) {
                $month += $v->seconds;
            }
            $total += $v->seconds;
        }

        return makeResponse(['today' => $today, 'week' => $week, 'month' => $month, 'total' => $total], '查询成功', 200);
    }

    public function rushOrderList(Request $request)
    {

        $longitude = $request->input('lng', 108.441719);//经度
        $longitude = 108.441719;//经度
        $latitude = $request->input('lat', 22.806061);//纬度
        $latitude = 22.806061;//纬度
        $range = 100000;//单位 m
        $staff_id = $request->input('staff_id');

        $arr = DB::select('select id,full_address,lng_address,lat_address,class_name,contacts,mobile,remarks,remark_img,created_at,ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $latitude . '*PI()/180-lat_address*PI()/180)/2),2)+COS(' . $latitude . '*PI()/180)*COS(lat_address*PI()/180)*POW(SIN((' . $longitude . '*PI()/180-lng_address*PI()/180)/2),2)))*1000) AS distance FROM commodity_orders  where commodity_orders.order_status=2 and created_at>DATE_SUB(NOW(), INTERVAL 190 MINUTE) having distance <= ' . $range . ' order by distance asc limit 10');

        foreach ($arr as &$v) {
            if ($v->remark_img) {
                $v->remark_img = json_decode($v->remark_img);
            } else {
                $v->remark_img = [];
            }
            $v->shengyu = strtotime($v->created_at) + 5400 - time();
        }
        return makeResponse($arr, '查询成功', 200);
    }

    public function versions()
    {
        $data = AppVersion::where(['type' => 1, 'status' => 1])->orderBy('id', 'desc')->select('id', 'version_number',
            'content', 'is_force', 'download_url', 'created_at')->first();
        return makeResponse($data, 'Success', 200);
    }
}